import { removeToken, setToken } from '@/utils/auth'
import { IRootState } from '@/store'
import { login } from '@/api/user'
import { ActionTree, Module, MutationTree } from 'vuex'
import { DEL_ALL_VIEWS, Logout, PASSWORD_LOGIN, RESET_TOEKN, SET_TOKEN } from '@/store/modules/methods-type'
import { ApiResponse } from '@/api/type'

export interface IUserInfo {
  username: string,
  password: string
}

export interface IUserState {
  token: string
}

type IMutations = MutationTree<IUserState>
type IActions = ActionTree<IUserState, IRootState>

const state: IUserState = {
  token: ''
}
const mutations: IMutations = {
  [SET_TOKEN](state, token: string) {
    state.token = token
  }
}

const actions: IActions = {
  [PASSWORD_LOGIN]({ commit }, userInfo: IUserInfo) {
    const { username, password } = userInfo
    return new Promise(async (resolve, reject) => {
      const res = await login({ username: username.trim(), password }),
        { data } = res as ApiResponse
      commit(SET_TOKEN, data)
      setToken(data)
      resolve(data)
    })
  },
  [Logout]({commit, dispatch}) {
    return new Promise<void>((resolve) => {
      commit(SET_TOKEN, '')
      removeToken()
      dispatch(`tagsView/${DEL_ALL_VIEWS}`, null, {root: true})
    })
  },
  [RESET_TOEKN]({commit}) {
    return new Promise<void>(resolve => {
      commit(SET_TOKEN, '')
      removeToken()
      resolve()
    })
  }
}

const user: Module<IUserState, IRootState> = {
  namespaced: true,
  state,
  actions,
  mutations
}
export default user

